package com.example.tliasmanagement.controller;

import com.aliyuncs.utils.StringUtils;
import com.example.tliasmanagement.aop.MyLog;
import com.example.tliasmanagement.dto.AddDeptDto;
import com.example.tliasmanagement.dto.UpdateDeptDto;
import com.example.tliasmanagement.entity.Dept;
import com.example.tliasmanagement.service.DeptService;
import com.example.tliasmanagement.util.JwtUtils;
import com.example.tliasmanagement.vo.DeptVo;
import com.example.tliasmanagement.vo.Result2;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    private DeptService deptService;

    //1. 接收参数
    @CrossOrigin(origins = {"http://127.0.0.1:5173","http://localhost:5173"})
    @GetMapping
    public Result2<List<DeptVo>> depts(HttpServletRequest request){
        // 先判断用户是否登录
        /*String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            return Result2.error("请登录以后再访问");
        }
        try{
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = claims.get("id", Integer.class);
            String username = claims.get("username", String.class);
            String name = claims.get("name", String.class);
            if(id == null || id <= 0){
                return Result2.error("请登录以后再访问");
            }
        }catch(Exception e){
            log.error(e.getMessage(), e);
            return Result2.error("请登录以后再访问");
        }*/
        //2. 调用service完成业务逻辑处理
        List<DeptVo> depts = deptService.depts();
        //3. 返回响应数据
        return Result2.ok(depts);
    }

    /**
     * 1. HttpServletRequest.getParameter("参数名")
     * 2. @RequestParam("参数名")
     * 3. controller的形参与前端传递参数名保持一致
     * */
    @MyLog(desc="删除部门")
    @DeleteMapping
   // public Result2<Void> deleteById(HttpServletRequest request) {
    //public Result2<Void>deleteById(@RequestParam("id")Integer id){
    public Result2<Void>deleteById(Integer id){
        deptService.deleteById(id);
        return  Result2.ok();
    }

    /**
     *
     * 路径变量  路径参数
     * @PathVariable
     */
    @MyLog(desc="新增部门")
    @PostMapping
    public Result2 addDept(@RequestBody AddDeptDto dto){
        deptService.addDept(dto);
        return  Result2.ok();
    }
    @GetMapping("/{id}")
    public Result2<Dept>getById(@PathVariable("id")Integer id){
        Dept dept=deptService.getById(id);
        return Result2.ok(dept);
    }
    @MyLog(desc="修改部门")
    @PutMapping
    public Result2 updateDept(@RequestBody UpdateDeptDto dto){
        // 调用service完成业务逻辑
        deptService.updateDept(dto);
        // 返回结果
        return Result2.ok();
    }


}
